<?php namespace App\Repositories\Eloquent\Tag;

use App\Models\Tag;
use App\Repositories\Tag\TagRepositoryInterface;

class TagRepository implements TagRepositoryInterface
{
    /**
     * 获取tag信息
     *
     * @param $name
     *
     * @return \Illuminate\Database\Eloquent\Model|null|\App\Models\Tag
     */
    public function getByName($name)
    {
        return Tag::query()->where('name', $name)->first();
    }

    /**
     * 新增tag
     *
     * @param $user_id
     * @param $name
     *
     * @return Tag|\Illuminate\Database\Eloquent\Model|null|\App\Models\Tag
     */
    public function store($user_id, $name)
    {
        $tag = $this->getByName($name);
        if ($tag) {
            return $tag;
        }

        $model = new Tag();
        $model->name = $name;
        $model->user_id = $user_id;
        $model->save();

        return $model;
    }

    /**
     * 获取系统指定类型的标签
     *
     * @param $type
     *
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|\App\Models\Tag[]
     */
    public function getByType($type)
    {
        return Tag::query()
            ->where(compact('type'))
            ->latest('sort')
            ->get();
    }
}
